﻿using Bigway.Common.Models.DbModels;
using SqlSugar;

namespace Benefactor.Models.DbModels;

public class RefererCommission: DeletableEntity
{
    [SugarColumn(IsNullable = false)]
    public string RefererAccount { get; set; }

    private double _totalRefererFee = 0;

    [SugarColumn(IsNullable = false)]
    public double TotalRefererFee
    {
        get
        {
            return RefererCommissionRecords is { Count: > 0 } &&
                   RefererCommissionWithdrawalRecords is not null
                ? RefererCommissionRecords
                      .Where(x => !x.IsDeleted)
                      .Sum(x => x.RefererFee) -
                  RefererCommissionWithdrawalRecords
                      .Where(x => !x.IsDeleted)
                      .Sum(x => x.Amount)
                : _totalRefererFee;
        }
        set => _totalRefererFee = value;
    }

    private List<RefererCommissionRecord>? _refererCommissionRecords;

    [Navigate(NavigateType.OneToMany,
        nameof(RefererCommissionRecord.RefererCommissionId))]
    public List<RefererCommissionRecord>? RefererCommissionRecords
    {
        get => _refererCommissionRecords;
        set
        {
            value?.Sort((x, 
                y) => y.CreateTime.CompareTo(x.CreateTime));
            _refererCommissionRecords = value;
        }
    }

    private List<RefererCommissionWithdrawalRecord>? _refererCommissionWithdrawalRecords;

    [Navigate(NavigateType.OneToMany,
        nameof(RefererCommissionWithdrawalRecord.RefererCommissionId))]
    public List<RefererCommissionWithdrawalRecord>? RefererCommissionWithdrawalRecords
    {
        get => _refererCommissionWithdrawalRecords;
        set
        {
            value?.Sort((x,
                y) => y.CreateTime.CompareTo(x.CreateTime));
            _refererCommissionWithdrawalRecords = value;
        }
    }
}